'use strict';

const Service = require('egg').Service;

class ResumeService extends Service {
  /**
   * 生成简历名称
   * 格式：YYYYMMDD_HHMMSS_姓名
   */
  generateResumeName(name) {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    
    return `${year}${month}${day}_${hours}${minutes}${seconds}_${name}`;
  }

  /**
   * 创建简历
   */
  async createResume(data) {
    const { ctx } = this;

    // 生成简历名称
    const resumeName = this.generateResumeName(data.basic_info.name);

<<<<<<< HEAD
    // 准备数据
    const resumeData = {
      user_id: data.user_id || 1,
=======
    // 处理照片上传
    let photoUrl = '';
    if (data.photo_url && data.photo_url.startsWith('data:image/')) {
      photoUrl = await this.savePhoto(data.photo_url, data.basic_info.name);
    }

    // 准备数据
    const resumeData = {
      user_id: data.user_id, // 必须从controller传入，不能使用默认值
>>>>>>> resume
      template_id: data.template_id,
      resume_name: resumeName,
      basic_info: data.basic_info,
      education_list: data.education_list || [],
      work_list: data.work_list || [],
      skills_list: data.skills_list || '',
<<<<<<< HEAD
      photo_url: data.photo_url || '',
=======
      photo_url: photoUrl,
>>>>>>> resume
      status: data.status || 1
    };

    // 创建简历
    const resume = await ctx.model.Resume.create(resumeData);
    
    return resume;
  }

  /**
<<<<<<< HEAD
=======
   * 保存照片到文件系统
   */
  async savePhoto(base64Data, userName) {
    const { ctx } = this;
    
    try {
      // 解析base64数据
      const matches = base64Data.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/);
      if (!matches) {
        throw new Error('Invalid base64 image data');
      }
      
      const imageType = matches[1];
      const imageData = matches[2];
      
      // 生成文件名：时间戳_姓名.扩展名
      const timestamp = Date.now();
      const fileName = `${timestamp}_${userName || 'user'}.${imageType}`;
      
      // 确保pictures目录存在
      const fs = require('fs');
      const path = require('path');
      const picturesDir = path.join(process.cwd(), 'app', 'public', 'pictures');
      
      if (!fs.existsSync(picturesDir)) {
        fs.mkdirSync(picturesDir, { recursive: true });
      }
      
      // 保存文件
      const filePath = path.join(picturesDir, fileName);
      fs.writeFileSync(filePath, imageData, 'base64');
      
      // 返回相对路径
      return `/pictures/${fileName}`;
    } catch (error) {
      ctx.logger.error('保存照片失败:', error);
      return '';
    }
  }

  /**
>>>>>>> resume
   * 获取简历列表
   */
  async getResumeList(query = {}) {
    const { ctx } = this;
<<<<<<< HEAD
    const { page = 1, pageSize = 100, user_id } = query;
    const offset = (page - 1) * pageSize;

=======
    const { page = 1, pageSize = 100, user_id, name } = query;
    const offset = (page - 1) * pageSize;

    // 设置where条件
>>>>>>> resume
    const where = {};
    if (user_id) {
      where.user_id = user_id;
    }
<<<<<<< HEAD
=======
    // 如果提供了name参数，进行模糊搜索
    if (name) {
      where.resume_name = { [ctx.app.Sequelize.Op.like]: `%${name}%` };
    }
>>>>>>> resume

    const result = await ctx.model.Resume.findAndCountAll({
      where,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['updated_at', 'DESC']]
    });

    return {
      total: result.count,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      list: result.rows
    };
  }

  /**
   * 获取简历详情
   */
  async getResumeById(id) {
    const { ctx } = this;
    const resume = await ctx.model.Resume.findByPk(id);
    
    if (!resume) {
      ctx.throw(404, '简历不存在');
    }
    
    return resume;
  }

  /**
   * 更新简历
   */
  async updateResume(id, data) {
    const { ctx } = this;
    
    const resume = await ctx.model.Resume.findByPk(id);
    if (!resume) {
      ctx.throw(404, '简历不存在');
    }

    // 如果修改了姓名，重新生成简历名称
    if (data.basic_info && data.basic_info.name) {
      data.resume_name = this.generateResumeName(data.basic_info.name);
    }

<<<<<<< HEAD
=======
    // 处理照片上传
    if (data.photo_url && data.photo_url.startsWith('data:image/')) {
      data.photo_url = await this.savePhoto(data.photo_url, data.basic_info?.name || resume.basic_info?.name);
    }

>>>>>>> resume
    await resume.update(data);
    return resume;
  }

  /**
   * 删除简历
   */
  async deleteResume(id) {
    const { ctx } = this;
    
    const resume = await ctx.model.Resume.findByPk(id);
    if (!resume) {
      ctx.throw(404, '简历不存在');
    }

    await resume.destroy();
    return { success: true };
  }
<<<<<<< HEAD
=======

  /**
   * 分享简历
   */
  async shareResume(id) {
    const { ctx } = this;
    
    const resume = await ctx.model.Resume.findByPk(id);
    if (!resume) {
      ctx.throw(404, '简历不存在');
    }

    // 更新状态为已发布并设置为已分享
    await resume.update({
      status: 3, // 已发布
      is_shared: 1 // 已分享
    });

    return resume;
  }

  /**
   * 取消分享简历
   */
  async unshareResume(id) {
    const { ctx } = this;
    
    const resume = await ctx.model.Resume.findByPk(id);
    if (!resume) {
      ctx.throw(404, '简历不存在');
    }

    // 取消分享
    await resume.update({
      is_shared: 0 // 未分享
    });

    return resume;
  }

  /**
   * 获取分享的简历列表
   */
  async getSharedResumeList(query = {}) {
    const { ctx } = this;
    const { page = 1, pageSize = 100 } = query;
    const offset = (page - 1) * pageSize;

    const result = await ctx.model.Resume.findAndCountAll({
      where: { 
        is_shared: 1 // 只获取已分享的简历
      },
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['updated_at', 'DESC']]
    });

    return {
      total: result.count,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      list: result.rows
    };
  }
>>>>>>> resume
}

module.exports = ResumeService;

